/*
* @Date: 2021/2/14
* @Author: XueChengwu <xuechengwu@erayt.com>
* @Copyright: 2015-2019 Erayt, Inc.
* @Description: If you have some questions, please contact: xuechengwu@erayt.com.
*/

class Ws {
  constructor(wsURL) {
    let ws = null;
    if (window.WebSocket) ws = new WebSocket(wsURL);
    if (window.MozWebSocket) ws = new MozWebSocket(wsURL);
    this.ws = ws;
    this.isReady = false;
    this.titles = {};
    this.onReadys = [];
    this.ws.onopen = (e) => {
      this.isReady = true;
      this.onReadys.forEach((func) => {
        func();
      });
    }
    this.ws.onmessage = (e) => {
      const msg = e.data || '';
      const cmds = msg.split(':');
      if (cmds.length > 0) {
        const title = cmds[0];
        if (this.titles[title]) {
          this.titles[title].forEach((vo) => {
            vo.callback && vo.callback({ data: msg.replace(`${cmds[0]}:`, ''), id: vo.id });
          });
        }
      }
    }
  }

  subscribe(titles, pageId) {
    const titleArr = [];
    for(let i = 0; i < titles.length; i++) {
      const title = titles[i];
      if (!this.titles[title.title]) {
        this.titles[title.title] = [];
      }
      const titleIndex = this.titles[title.title].findIndex(vo => vo.id === pageId);
      if (titleIndex === -1) {
        this.titles[title.title].push({
          callback: title.callback,
          id: pageId,
        });
      }
      titleArr.push(title.title);
    }
    if (this.isReady) {
      this.ws.send(`A:${titleArr.join(',')}`);
    } else {
      this.onReadys.push(() => {
        this.ws.send(`A:${titleArr.join(',')}`);
      });
    }
  }
  unsubscribe(title, pageId, isStop = false) {
    if (this.titles[title]) {
      if (!pageId || isStop) {
        delete this.titles[title]
      } else {
        const tIndex = this.titles[title.title].findIndex(vo => vo.id === pageId);
        if (tIndex >= 0) {
          this.titles[title].splice(tIndex, 1);
        }
      }
    }
    if (isStop) {
      this.ws.send(`D:${title}`);
    }
  }
}

const ws = new Ws('ws://127.0.0.1:18880/');
export default ws;
